//
//  YYCityViewController.m
//  YYWeather
//
//  Created by 姚英 on 16/7/5.
//  Copyright © 2016年 yy. All rights reserved.
//

#import "YYCityViewController.h"
#import "Public.h"
#import "HeadView.h"
#import "CityViewCell.h"

#import "YYSearchResultController.h"
#import "YYSearchController.h"
// 获取搜索的结果集
//#import "SearchResult.h"
// 过滤器 过相同滤掉的元素
//#import "NSMutableArray+FilterElement.h"
// 跟控制器
//#import "RootViewController.h"

#import <INTULocationManager.h>

#import <CoreLocation/CoreLocation.h>
#import "SQLOperation.h"

#import <SVProgressHUD/SVProgressHUD.h>


#import "UIImage+Image.h"

//<UISearchControllerDelegate,UISearchResultsUpdating,UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate,CLLocationManagerDelegate,NBSearchResultControllerDelegate,CityViewCellDelegate>

@interface YYCityViewController () <UISearchControllerDelegate,UISearchResultsUpdating, UISearchBarDelegate ,CityViewCellDelegate, UITableViewDataSource, UITableViewDelegate, YYSearchResultControllerDelegate>

///
@property(nonatomic, weak) UITableView *tableView;
// 当前城市
@property(nonatomic, strong) NSString *locationCity;
/// 热门城市
@property(nonatomic, strong) NSArray *hotCity;
/// 最近访问
@property(nonatomic, strong) NSArray *latestCity;

/// 当前、最近、热门城市
@property(nonatomic, strong)  NSMutableArray * dataCity; //定位当前城市;


/// 搜索的结果控制器
@property (nonatomic, weak)YYSearchResultController *searchResultController;
/// 搜索的控制器
@property (nonatomic, strong)YYSearchController *searchController;
/// 搜索结果
//@property(nonatomic, strong) NSArray *searchList;



///
//@property(nonatomic, weak) UISearchController *searchController;

/// 定位，最近，热门数据原
//@property(nonatomic, strong) NSMutableArray *dataArray;
///// 城市首字母
//@property(nonatomic, strong) NSMutableArray *keys;

@end

@implementation YYCityViewController

// 用于提示授权位置服务的标志
static BOOL auth_HUD_flag = 0;

#pragma mark - 生命周期方法

- (void)viewDidLoad {
    [super viewDidLoad];

//    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"ID"];
//    self.tableView.style = UITableViewStylePlain;

    [self setupTableView];
    
    // 获取当前位置
    [self locate];
    // 读取列表数据
    [self loadData];
    // 初始化tableView	
    //[self initTableView];
    //初始化搜索框
    [self initSearchController];
}

- (void)viewWillAppear:(BOOL)animated{
    
//    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    
    UIImage *img = [UIImage imageWithColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar setBackgroundImage:img forBarMetrics:UIBarMetricsDefault];
    
//    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
//    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
//    self.navigationItem.backBarButtonItem = item;
    
    // 设置导航条阴影背景
    self.navigationItem.backBarButtonItem.title = @"返回";
}


#pragma mark - 设置

-(void)setupTableView{
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView = tableView;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    _tableView.sectionIndexColor = RGB(150, 150, 150);
    [self.view addSubview:_tableView];
}


#pragma mark -获取当前位置

- (void)locate{
    
    _locationCity = @"获取中..";
    
    INTULocationManager *locMgr = [INTULocationManager sharedInstance];
    [locMgr requestLocationWithDesiredAccuracy:INTULocationAccuracyCity
                                       timeout:6.0
                          delayUntilAuthorized:YES  // This parameter is optional, defaults to NO if omitted
                                         block:^(CLLocation *currentLocation, INTULocationAccuracy achievedAccuracy, INTULocationStatus status) {
                                             
                                             NSLog(@"status = %li",(long)status);
                                             NSLog(@"currentLocation = %@",currentLocation);
                                             if (status == INTULocationStatusSuccess) {
                                                 YYLog(@"获取成功")
                                                 CLGeocoder *geocoder = [[CLGeocoder alloc] init];
                                                 
                                                 [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
                                                  {
                                                      
                                                      if (array.count > 0)
                                                      {
                                                          CLPlacemark *placemark = [array objectAtIndex:0];
                                                          //NSLog(@%@,placemark.name);//具体位置
                                                          //获取城市
                                                          NSString *city = placemark.locality;
                                                          YYLog(@"city = %@",city)
                                                          if (!city) {
                                                              //未知的
                                                              city = placemark.administrativeArea;
                                                              YYLog(@"city is nil, administrativeArea = %@",city)
                                                          }
                                                          // 设置城市
                                                          _locationCity = city;
                                                          NSLog(@"writeLocationCity = %i", [SQLOperation writeLocationCity:_locationCity]);
                                                          //修改数据
                                                          self.dataCity[0] = [NSArray arrayWithObject:_locationCity];
                                                          //写数据到数据库
                                                          
                                                          // 刷新表格
                                                          NSIndexSet *index = [NSIndexSet indexSetWithIndex:0];
                                                          [self.tableView reloadSections:index withRowAnimation:UITableViewRowAnimationNone];

                                                      }else if (error == nil && [array count] == 0)
                                                      {
                                                          YYLog(@"No results were returned.")
                                                      }else if (error != nil)
                                                      {
                                                          // 无网络，也会来到这里。
                                                          _locationCity = @"无法获取";
                                                          self.dataCity[0] = [NSArray arrayWithObject:_locationCity];
                                                          // 刷新表格
                                                          NSIndexSet *index = [NSIndexSet indexSetWithIndex:0];
                                                          [self.tableView reloadSections:index withRowAnimation:UITableViewRowAnimationNone];
                                                          YYLog(@"An error occurred = %@", error)
                                                      }
                                                  }];
                                                 
                                             }
                                             else if (status == INTULocationStatusTimedOut) {
                                                 _locationCity = @"无网络";
                                                 YYLog(@"获取位置超时,请检查网络")
                                             }
                                             else if(status == INTULocationStatusServicesNotDetermined){
                                                 _locationCity = @"无法获取";
                                                 YYLog(@"位置服务未设置")
                                             }
                                             else if(status == INTULocationStatusServicesDenied){
                                                 _locationCity = @"未授权";
                                                 if (auth_HUD_flag == 1) {
                                                     // 提示开启授权
                                                     [SVProgressHUD showInfoWithStatus:@"请在：设置->隐私->定位服务 中开启授权!"];
                                                     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
                                                         
                                                         [SVProgressHUD dismiss];
                                                     });
                                                     auth_HUD_flag = 0;
                                                 }
                                                 
                                                 YYLog(@"位置服务未授权")
                                             }
                                             else if(status == INTULocationStatusServicesRestricted){
                                                 _locationCity = @"无法获取";
                                                 YYLog(@"位置服务受限制")
                                             }
                                             else if(status == INTULocationStatusServicesDisabled){
                                                 _locationCity = @"无法获取";
                                                 YYLog(@"请在设置页面打开位置服务")
                                             }
                                             else{
                                                 _locationCity = @"无法获取";
                                                 YYLog(@"未知的错误")
                                             }
                                             // 刷新表格
                                             if (_locationCity == nil) {
                                                 _locationCity = @"正在获取位置";
                                             }
                                             YYLog(@"当前城市 = %@", _locationCity)
                                            
                                             self.dataCity[0] = [NSArray arrayWithObject:_locationCity];
                                             // 刷新表格
                                             NSIndexSet *index = [NSIndexSet indexSetWithIndex:0];
                                             [self.tableView reloadSections:index withRowAnimation:UITableViewRowAnimationNone];
                                         }];
}

#pragma mark - 读取数据
-(void)loadData{
    
    // 打开数据库
    [SQLOperation openDB];
    
    //定位城市
     NSArray *locationCity = [SQLOperation readLocationCity];
    YYLog(@"locationCity = %@",locationCity)
    [self.dataCity addObject:locationCity];
    
    //最近访问
    NSArray *latesCity = [SQLOperation readLastCity];
    YYLog(@"latesCity = %@",latesCity)
    [self.dataCity addObject:latesCity];
    
    //热门城市
    NSArray *hotCity = [SQLOperation readHotCity];
    YYLog(@"hotCity = %@",hotCity)
    [self.dataCity addObject:hotCity];
    
    YYLog(@"hotCity = %@",self.dataCity)
}

-(void)initSearchController //创建搜索控制器
{
    YYSearchResultController *searchResultController = [[YYSearchResultController alloc]init];
    _searchResultController = searchResultController;
    searchResultController.delegate = self;
    [self addChildViewController:searchResultController];
    
    _searchController = [[YYSearchController alloc]initWithSearchResultsController:self.searchResultController];;
    _searchController.hidesNavigationBarDuringPresentation = YES;
    _searchController.delegate = self;
    _searchController.searchResultsUpdater = self;
    _searchController.searchBar.delegate = self;
    self.tableView.tableHeaderView = self.searchController.searchBar;
}

//修改SearchBar的Cancel Button 的Title
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar;
{
    [_searchController.searchBar setShowsCancelButton:YES animated:YES];
    UIButton *btn = [_searchController.searchBar valueForKey:@"_cancelButton"];
    [btn setTitle:@"取消" forState:UIControlStateNormal];
}

#pragma mark - <UITableViewDataSource, UITableViewDelegate>


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identfire=@"Cell";
    
    CityViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identfire];
    
    if (!cell) {
        
        cell=[[CityViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identfire];
    }
    
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setContentView:self.dataCity[indexPath.section]];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{	
     HeadView  *CellHeadView=[[HeadView alloc]init];
    
    if (section==0) {
        
        CellHeadView.TitleLable.text=@"当前城市";
    }else if (section==1){
        
        CellHeadView.TitleLable.text=@"最近访问";
        
    }
    else if (section==2){
        
        CellHeadView.TitleLable.text=@"热门城市";
        
    }else{
#warning --
        CellHeadView.TitleLable.text= @"haha";
    }
    
    return CellHeadView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section <= 2) {
        return [CityViewCell getHeightWithCityArray:self.dataCity[indexPath.section]];
    }else{
        
        return 47;
    }
    return 0;
}



#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    NSString *searchString = [self.searchController.searchBar text];
//    NSLog(@"--a%@",searchString);
    // 还未输入搜索内容
    if (searchString == nil || searchString.length == 0) {
        return;
    }
    // 按城市拼音首字母搜索
    self.searchResultController.dataSource = [SQLOperation readCityList:searchString];
    
//    // 如果搜索不到内容，则按汉字搜索
//    if (self.searchResultController.dataSource.count == 0 ) {
//         self.searchResultController.dataSource = [SQLOperation readCityNameList:searchString];
//    }
    
    [self.searchResultController.tableView reloadData];
}


-(void)SelectCityNameInCollectionBy:(NSString *)cityName
{
    YYLog(@"%@",cityName)
    //对city先进行处理，去除“市”等干扰字符，数据库里没有带“市”，网络请求中带“市”也请求不到数据
    //逻辑：1、先对city进行精确搜索，得到唯一结果则写入数据库后跳转
    //     2、如果精确搜索不到，则以city的前两个关键字进行模糊查询，得到的结果如是唯一结果，则结束,否则弹出暂无该城市数据
    if ([cityName isEqualToString:@"获取中.."]) {
        [self locate];
        return;
    }else if([cityName isEqualToString:@"未授权"]) {
        //重新定位
        [self locate];
        
        //设置一个标志位，在定位程序中发现该标志位为1，则弹出提示。
        auth_HUD_flag = 1;
        
        // 提示开启授权
//        [SVProgressHUD showInfoWithStatus:@"请在：设置->隐私->定位服务 中开启授权!"];
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
//            
//            [SVProgressHUD dismiss];
//        });
        return;

    }else if([cityName isEqualToString:@"无网络"]) {
        //重新定位
        [self locate];
        return;
        
    }else if([cityName isEqualToString:@"无法获取"]) {
        //重新定位
        [self locate];
        return;
    }
    

    NSString *city = [SQLOperation readCity:cityName];
    YYLog(@"%@",city)
    // 1、
    if (city == nil) {
        // 2、
        YYLog(@"%lu",(unsigned long)cityName.length)
        city = [SQLOperation readCity:[cityName substringToIndex:2]];
        YYLog(@"substr = %@",city);
        if (city == nil) {
            YYLog(@"暂无该城市数据")
            
            [SVProgressHUD showInfoWithStatus:@"暂无该城市数据"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
                
                [SVProgressHUD dismiss];
            });
            return;
        }
    }
    

    [SQLOperation writeLastCity:city];
    [self popRootViewControllerWithName:city];
}

- (void)popRootViewControllerWithName:(NSString *)cityName
{
//    self.returnBlock(cityName);
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark - 懒加载
-(NSMutableArray *)dataCity{
    if(_dataCity == nil){
        
        _dataCity = [NSMutableArray array];
    }
    return _dataCity;
}

#pragma mark - test

//-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    static int count = 0;
//    
//    YYLog(@"更新数据库 %i 次 ", count)
//    if (count % 2 == 0) {
//        [SQLOperation writeLastCity:@"长沙"];
//    }else{
//        [SQLOperation writeLastCity:@"深圳"];
//    }
//    
//    count++;
//}

/**
 *  点击了搜索的结果的 cell
 *
 *  @param resultVC  搜索结果的控制器
 *  @param follow    搜索结果信息的模型
 */
- (void)resultViewController:(YYSearchResultController *)resultVC didSelectFollowCity:(NSString *)cityName
{
    [self.searchController dismissViewControllerAnimated:NO completion:nil];
    [self SelectCityNameInCollectionBy:cityName];
}
@end
